import java.text.ParseException;
import java.util.Arrays;

public class MyList {
    public int[] elem;
    public int size;
    private static final int DEFAULT_SIZE = 10;

    public MyList( ) {
        this.elem = new int[DEFAULT_SIZE];
    }

    // 打印顺序表
    public void display() {
        for (int i = 0; i < this.size; i++) {
            System.out.print(elem[i]+" ");
        }
        System.out.println();
    }
    // 新增元素,默认在数组最后新增
    public void add(int data) {
        if(isFull()){
            this .elem = Arrays.copyOf(elem,2*elem.length);
        }
        this.elem[this.size] = data;
        this.size++;
    }
    // 在 pos 位置新增元素
    public void add(int pos, int data) throws PosWrongfulException {
        if(isFull()){
            this.elem = Arrays.copyOf(elem,2*elem.length);
        }
        if(pos < 0||pos > this.size){
            throw new PosWrongfulException("pos位置不合法");
        }
        for (int i = this.size; i >= pos; i--) {
            this.elem[i+1] = this.elem[i];
        }
        this.elem[pos] = data;
        this.size++;
    }
// 判定是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < this.size; i++) {
            if(this.elem[i] == toFind){
                return true;
            }
        }
        return false;
    }
    // 查找某个元素对应的位置
    public int indexOf(int toFind) {
        for (int i = 0; i < this.size; i++) {
            if(this.elem[i] == toFind ){
                return i;
            }
        }
        return -1;
    }
    // 获取 pos 位置的元素
    public int get(int pos) {
        if(isEmpty()){
         throw new EmptyException("该链表为空");
        }
        if(pos < 0||pos >= this.size){
            throw new PosWrongfulException("pos不合法异常");
        }
        return this.elem[pos];
    }
    public boolean isEmpty(){
        return size() == 0;
    }
    // 给 pos 位置的元素设为 value
    public void set(int pos, int value) {
        if(isEmpty()){
           throw new EmptyException("该链表为空");
        }
        if(pos <0 ||pos >= this.size){
            throw new RuntimeException("pos不合法异常");
        }
        this.elem[pos] = value;
    }
    //删除第一次出现的关键字key
    public void remove(int Key) {
        if(isEmpty()){
            throw new EmptyException("该链表为空！");
        }
        int index = this.indexOf(Key);
        if(index == -1){
            System.out.println("没有该数字");
            return;
        }
        for (int i = index; i < size - 1; i++) {
               this.elem[i] = this.elem[i+1];
        }
        this.size--;
    }
    // 获取顺序表长度
    public int size() {
        return this.size;
    }
    // 清空顺序表
    public void clear() {
        this.size = 0;
    }
    public boolean isFull(){
        return this.size >= this.elem.length;
    }
}

